//
//  PPTimelineUserObject.m
//  pickpic
//
//  Created by Jinxiao on 10/6/16.
//  Copyright © 2016 MicroDream. All rights reserved.
//

#import "PPTimelineUserObject.h"

@implementation PPTimelineUserObject

+ (instancetype)userForParameters:(NSDictionary *)parameters {
    PPTimelineUserObject *user = [[PPTimelineUserObject alloc] init];

    user.name = [parameters validStringForKey:@"name"];
    user.userID = [parameters validStringForKey:@"user"] ?: [parameters validStringForKey:@"id"];
    user.avatarHost = [parameters validStringForKey:@"avatarHost"];
    user.avatarKey = [parameters validStringForKey:@"avatar"];

    return user;
}

- (NSString *)avatarURLString {
    if([self.avatarKey length] == 0 || [self.avatarHost length] == 0) {
        return nil;
    }

    if([self.avatarKey hasPrefix:@"http:"]) {
        return self.avatarKey;
    }

    return [NSString stringWithFormat:@"%@%@", self.avatarHost, self.avatarKey];
}

- (void)encodeWithCoder:(NSCoder *)encoder {
    [encoder encodeObject:self.userID forKey:@"userID"];
    [encoder encodeObject:self.name forKey:@"name"];
    [encoder encodeObject:self.avatarHost forKey:@"avatarHost"];
    [encoder encodeObject:self.avatarKey forKey:@"avatarKey"];
}

- (id)initWithCoder:(NSCoder *)decoder {
    self = [super init];

    if(self) {
        self.userID = [decoder decodeObjectForKey:@"userID"];
        self.name = [decoder decodeObjectForKey:@"name"];
        self.avatarHost = [decoder decodeObjectForKey:@"avatarHost"];
        self.avatarKey = [decoder decodeObjectForKey:@"avatarKey"];
    }

    return self;
}

@end
